package cn.ym.controller;

import cn.ym.domain.User;
import cn.ym.exception.BusinessException;
import cn.ym.query.UserQuery;
import cn.ym.service.UserService;
import cn.ym.utils.AjaxResult;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
/**
 * 用户的接口
 */
@RestController
@RequestMapping("/user")
@Api(value = "用户的接口的API",description="用户的接口的CRUD功能")
public class UserController {

    @Autowired
    private UserService userService;

    //添加或修改用户信息
    @PutMapping
    @ApiOperation(value = "添加+修改" )
    public AjaxResult save(@RequestBody User user, HttpSession session){
        try {
            if(user.getId()==null){
                userService.add(user,session);
            }else {
                userService.update(user,session);
            }
            return new AjaxResult();
        } catch (BusinessException e) {
            return new AjaxResult(false,e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"系统异常，请稍后重试");
        }

    }

    //删除用户信息
    @ApiOperation(value = "通过ID删除" )
    @DeleteMapping("/{id}")
    public AjaxResult del(@PathVariable("id") Long id){
        try {
            userService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();//打印错误信息
            return  new AjaxResult(false,"网络异常，请稍后重试");
        }
    }

    //查询所有用户信息
    @ApiOperation(value = "查询使用用户" )
    @GetMapping
    public List<User> findAll(){
        return userService.findAll();
    }

    //查询单个用户信息
    @ApiOperation(value = "通过ID查询" )
    @GetMapping("/{id}")
    public User findOne(@PathVariable("id") Long id){
        return userService.findOne(id);
    }


    //分页查询 + 高级查询
    @PostMapping
    @ApiOperation(value = "分页+高级" )
    public PageInfo<User> queryPage(@RequestBody UserQuery userQuery){
        List<User> users = userService.queryPage(userQuery);
        return new PageInfo<>(users);
    }

    //批量删除用户信息
    @ApiOperation(value = "通过ID删除" )
    @PatchMapping
    public AjaxResult Patchdel(@RequestBody Long[]  ids){
        try {
            userService.Patchdel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();//打印错误信息
            return  new AjaxResult(false,"网络异常，请稍后重试");
        }
    }
}